import dash
from flask_login import LoginManager, UserMixin

from model import UserAccount
from flask import request, send_from_directory
import os
from config import PathConfig

app = dash.Dash(
    __name__,
    suppress_callback_exceptions=True,
    update_title=None
)

server = app.server

app.title = '净值分析测试平台'

# 初始化登陆管理类
login_manager = LoginManager()

login_manager.login_view = '/'

# 配置密钥
app.server.secret_key = 'my dash app'

# 绑定纳入鉴权范围的flask实例
login_manager.init_app(server)


class User(UserMixin):
    pass


@login_manager.user_loader
def load_user(user_id):

    match_user = list(
        UserAccount
        .select()
        .where(UserAccount.username == user_id)
        .dicts()
    )[0]

    curr_user = User()
    curr_user.id = user_id
    curr_user.role = match_user['role']
    curr_user.gender = match_user['gender']
    curr_user.register_time = match_user['register_time']

    return curr_user


@app.server.route('/upload', methods=['POST'])
def upload():
    """
    构建上传服务
    """
    # 获取上传id参数，用于指向保存路径
    upload_id = request.values.get('uploadId')

    # 获取上传文件的名称
    filename = request.files['file'].filename

    try:
        os.mkdir(os.path.join(PathConfig.ABS_ROOT_PATH, 'caches', upload_id))
    except FileExistsError:
        pass

    # 流式写出文件到指定目录
    with open(os.path.join(PathConfig.ABS_ROOT_PATH, 'caches', upload_id, filename), 'wb') as f:
        # 流式写出大型文件，这里的10代表10MB
        for chunk in iter(lambda: request.files['file'].read(1024 * 1024 * 10), b''):
            f.write(chunk)

    return {'filename': filename}


@app.server.route('/download')
def download():
    """
    构建下载服务
    """
     # 提取文件路径参数
    # path = request.values.get('path'),

    # 提取文件名称参数
    file = request.values.get('file')

    return send_from_directory(os.path.join(PathConfig.ABS_ROOT_PATH, 'caches/template'), file)